import {
	Client
} from "@twilio/conversations";
import {
	computed,
	onUnmounted,
	ref,
	shallowRef,
	toValue,
	watch,
	watchEffect
} from "vue";

export const useCommunication = ({
	token
}) => {
	// 是否初始化标识结束
	const disable = ref(true);

	let client;

	// 当前用户标识

	const myIdentity = ref(null);

	// 销毁
	const destroy = () => {
		if (!client) {
			return;
		}
		client.shutdown();
	};

	// 错误消息
	const error = ref();

	watchEffect(onCleanup => {
		if (!toValue(token)) {
			return;
		}
		client = new Client(token.value);
		client.on("stateChanged", async state => {
			if (state === "initialized") {
				// 拉取一次会话列表
				await pullMessages();
				disable.value = false;
				myIdentity.value = client.user.identity;
			}
		});

		client.on("connectionError", err => {
			error.value = err;
			disable.value = true;

			console.error("Connection error:", err);
		});
		onCleanup(() => {
			destroy();
		});
	});

	onUnmounted(() => {
		destroy();
	});

	let currentConversation = ref();

	let fn;

	watch(currentConversation, () => {
		if (currentConversation.value) {
			currentConversation.value.on("messageAdded", message => {
				conversationHistory.value.push(message);
				console.log(`监听到消息回调`, message);
				fn?.(message);
			});
		}
	});

	// 发送消息
	const send = async message => {
		if (!available.value) {
			return;
		}

		await currentConversation.value.sendMessage(message);
	};

	// 接收消息
	const receiveMessages = f => {
		fn = f;
	};

	// 历史会话记录列表
	const conversations = shallowRef([]);

	// 拉取会话记录
	const pullMessages = async () => {
		const _conversations = await client.getSubscribedConversations();
		// 历史原因,过滤掉没有会话标题的
		conversations.value = _conversations.items.filter(f => f.uniqueName);
	};

	// 给定会话获取会话消息列表
	const getMessage = async conversation => {
		if (!conversation) {
			return;
		}
		const messages = await conversation.getMessages();
		return messages.items;
	};

	const storeInformation = shallowRef({
		yourLogo: "",
		// 是否允许切换
		switching: false
	});

	// 切换绑定,注册绑定信息,等待watch执行
	const switchBinding = async ({
		yourLogo
	}) => {
		storeInformation.value = {
			yourLogo,
			switching: true
		};
	};

	// 每条会话的消息列表
	const conversationHistory = ref([]);

	watch([disable, storeInformation, conversations], async () => {
		if (disable.value) {
			return;
		}
		const {
			yourLogo,
			switching
		} = storeInformation.value;
		// 必须有会话id
		if (!switching || !yourLogo) {
			return;
		}

		const next = async () => {
			const result = await filterConversationsByUser(yourLogo);
			if (!result) {
				throw new Error(`查找历史会话失败`);
			}

			currentConversation.value = await client.getConversationByUniqueName(result.uniqueName);
			return result;
		};

		// 创建新会话
		const created = async () => {
			currentConversation.value = await client.createConversation({
				uniqueName: `chat-${Date.now()}`
			});
			await currentConversation.value.add(client.user.identity);
			// 添加对方用户
			await currentConversation.value.add(yourLogo);
		};

		// 先尝试查找会话,如果找不到则创建新会话

		try {
			const result = await next();
			// 这里直接取当前的消息列表，但是如果进入catch说明新创建直接清空即可
			const history = await getMessage(result);
			conversationHistory.value = history;
		} catch {
			conversationHistory.value = [];
			await created();
			await pullMessages();
		}
		storeInformation.value.switching = false;
		console.log(`切换历史回话成功`);

		return;
	});

	// 筛选指定会话id
	const filterConversationsByUser = async userId => {
		for (const conversation of conversations.value) {
			const participants = await conversation.getParticipants();

			const userInConversation = participants.find(participant => participant.identity === userId);

			if (userInConversation) {
				return conversation;
			}
		}
	};

	// 是否允许使用
	const available = computed(() => {
		return !disable.value && currentConversation.value && !storeInformation.value.switching;
	});

	return {
		conversationHistory,
		available,
		switchBinding,
		send,
		receiveMessages,
		pullMessages,
		// 所有对话列表
		conversations,
		getMessage,
		myIdentity,
		error
	};
};